import sys
import traceback

import yaml
import time
import threading
import requests
import config
import eventlet.green.threading
import eventlet.queue
from engineio import async_eventlet

from app import app, socketio

host = '0.0.0.0'
port = 8090

auto_run = False
proxy_cfg = None


def auto_start(base_url, cfg):
    time.sleep(10)
    print('call', cfg)
    try:
        requests.post(base_url + 'running/run', data=dict(address=cfg['Addr'], port=cfg['Port'], tasks=cfg['Tasks']))
    except:
        traceback.print_exc()

try:
    f = open("MemcachedProxy.yaml")
    cfg = yaml.load(f)
    f.close()
    port = int(cfg['HttpPort'])
    val = cfg['AutoRun']
    if isinstance(val, bool):
        auto_run = val
    elif isinstance(val, str):
        val = val.lower()
        if val in ('on', 'true'):
            auto_run = True
    proxy_cfg = cfg['Proxy']
except:
    pass

port_arg_index = 1
if getattr( sys, 'frozen', False ) :
    port_arg_index = 2
    print(sys.argv)


try:
    port = int(sys.argv[port_arg_index])
except:
    pass

print('host:', host)
print('port:', port)

setattr(app, 'base_url', 'http://%s:%d/'%('127.0.0.1' if host=='0.0.0.0' else host, port))
if proxy_cfg:
    t = threading.Thread(target=auto_start, args=(app.base_url, proxy_cfg,))
    t.start()

socketio.run(app, host=host, port=port, debug=False, use_reloader=False)

